function [MOVINGREG] = autoRegisterWidefield_v1_5(MOVING,FIXED)
%registerImages  Register grayscale images using auto-generated code from Registration Estimator app.
%  [MOVINGREG] = registerImages(MOVING,FIXED) Register grayscale images
%  MOVING and FIXED using auto-generated code from the Registration
%  Estimator app. The values for all registration parameters were set
%  interactively in the app and result in the registered image stored in the
%  structure array MOVINGREG.

% Auto-generated by registrationEstimator app on 25-Jan-2023
%-----------------------------------------------------------

%% do some image inversion:
curim = MOVING;
curim = imcomplement(curim);
curim = curim - min(curim(:));
a = mode(curim(:));
msk = curim == a;
temp = curim(~msk);%temp = temp(:);
floorval = prctile(temp,5);
curim(msk) = floorval;
curim = curim-floorval;
curim(curim<0) = 0;
MOVING = curim;

curim = FIXED;
curim = imcomplement(curim);
curim = curim - min(curim(:));
a = mode(curim(:));
msk = curim == a;
temp = curim(~msk);%temp = temp(:);
floorval = prctile(temp,5);
curim(msk) = floorval;
curim = curim-floorval;
curim(curim<0) = 0;
FIXED = curim;


% Normalize FIXED image

% Get linear indices to finite valued data
finiteIdx = isfinite(FIXED(:));

% Replace NaN values with 0
FIXED(isnan(FIXED)) = 0;

% Replace Inf values with 1
FIXED(FIXED==Inf) = 1;

% Replace -Inf values with 0
FIXED(FIXED==-Inf) = 0;

% Normalize input data to range in [0,1].
FIXEDmin = min(FIXED(:));
FIXEDmax = max(FIXED(:));
if isequal(FIXEDmax,FIXEDmin)
    FIXED = 0*FIXED;
else
    FIXED(finiteIdx) = (FIXED(finiteIdx) - FIXEDmin) ./ (FIXEDmax - FIXEDmin);
end

% Normalize MOVING image

% Get linear indices to finite valued data
finiteIdx = isfinite(MOVING(:));

% Replace NaN values with 0
MOVING(isnan(MOVING)) = 0;

% Replace Inf values with 1
MOVING(MOVING==Inf) = 1;

% Replace -Inf values with 0
MOVING(MOVING==-Inf) = 0;

% Normalize input data to range in [0,1].
MOVINGmin = min(MOVING(:));
MOVINGmax = max(MOVING(:));
if isequal(MOVINGmax,MOVINGmin)
    MOVING = 0*MOVING;
else
    MOVING(finiteIdx) = (MOVING(finiteIdx) - MOVINGmin) ./ (MOVINGmax - MOVINGmin);
end

% Default spatial referencing objects
fixedRefObj = imref2d(size(FIXED));
movingRefObj = imref2d(size(MOVING));

% Phase correlation
tform = imregcorr(MOVING,movingRefObj,FIXED,fixedRefObj,'transformtype','similarity','Window',true);
MOVINGREG.Transformation = tform;
MOVINGREG.RegisteredImage = imwarp(MOVING, movingRefObj, tform, 'OutputView', fixedRefObj, 'SmoothEdges', true);

% Nonrigid registration
[MOVINGREG.DisplacementField,MOVINGREG.RegisteredImage] = imregdemons(MOVINGREG.RegisteredImage,FIXED,100,'AccumulatedFieldSmoothing',1.0,'PyramidLevels',3);

% Store spatial referencing object
MOVINGREG.SpatialRefObj = fixedRefObj;

end

